<template>
  <div class="api-management">
    <!-- 页面标题区域 -->
    <div class="page-header glass-effect">
      <div class="header-content">
        <h1>我的 API</h1>
        <div class="header-actions">
          <el-button type="primary" @click="createApi">
            <i class="el-icon-plus"></i> 创建新接口
          </el-button>
        </div>
      </div>
      
      <!-- 统计卡片区域 -->
      <div class="stats-cards">
        <div class="stat-card glass-effect">
          <div class="stat-icon">
            <i class="el-icon-upload2"></i>
          </div>
          <div class="stat-info">
            <span class="stat-value">{{ stats.published }}</span>
            <span class="stat-label">已发布</span>
          </div>
        </div>
        
        <div class="stat-card glass-effect">
          <div class="stat-icon">
            <i class="el-icon-warning-outline"></i>
          </div>
          <div class="stat-info">
            <span class="stat-value">{{ stats.offline }}</span>
            <span class="stat-label">已下架</span>
          </div>
        </div>
        
        <div class="stat-card glass-effect">
          <div class="stat-icon">
            <i class="el-icon-edit-outline"></i>
          </div>
          <div class="stat-info">
            <span class="stat-value">{{ stats.draft }}</span>
            <span class="stat-label">草稿</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section glass-effect">
      <el-input
        v-model="searchQuery"
        placeholder="搜索接口名称或描述"
        prefix-icon="el-icon-search"
        clearable
        class="search-input"
      />
      <el-select v-model="statusFilter" placeholder="状态筛选" class="status-filter">
        <el-option label="全部" value="" />
        <el-option label="已发布" value="1" />
        <el-option label="已下架" value="0" />
        <el-option label="待审核" value="-2" />
        <el-option label="审核失败" value="-3" />
        <el-option label="预发布" value="20" />
      </el-select>
    </div>

    <!-- API 列表区域 -->
    <div class="api-list" v-loading="loading">
      <el-card 
        v-for="api in filteredApis" 
        :key="api.apiid" 
        class="api-card glass-effect"
        :class="getCardClass(api.status)"
      >
        <div class="api-header">
          <div class="api-title">
            <h3>{{ api.name }}</h3>
            <el-tag 
              :type="getStatusType(api.status)"
              effect="dark"
              size="small"
            >
              {{ getStatusLabel(api.status) }}
            </el-tag>
          </div>
          <div class="api-actions">
            <el-tooltip content="编辑" placement="top">
              <el-button 
                type="primary" 
                icon="el-icon-edit" 
                circle
                size="small"
                @click="editApi(api)"
              ></el-button>
            </el-tooltip>
            <template v-if="api.status === -1">
  <el-tooltip content="发布" placement="top">
    <el-button 
      type="success" 
      icon="el-icon-upload2"
      circle
      size="small"
      @click="publishApi(api)"
    ></el-button>
  </el-tooltip>
</template>
            
            <!-- 参数配置按钮 -->
            <template v-if="api.status === 10">
              <el-tooltip content="配置参数" placement="top">
                <el-button 
                  type="info" 
                  icon="el-icon-setting" 
                  circle
                  size="small"
                  @click="configureParameters(api)"
                ></el-button>
              </el-tooltip>
            </template>
            
            <!-- 预发布状态显示配置发布按钮 -->
            <template v-if="api.status === 20 || api.status === -1">
              <el-tooltip content="配置发布" placement="top">
                <el-button 
                  type="warning" 
                  icon="el-icon-setting"
                  circle
                  size="small"
                  @click="configurePublish(api)"
                ></el-button>
              </el-tooltip>
            </template>
            
            <!-- 审核失败状态显示查看原因和重新发布按钮 -->
            <template v-if="api.status === -3">
              <el-tooltip content="查看失败原因" placement="top">
                <el-button 
                  type="warning" 
                  icon="el-icon-warning"
                  circle
                  size="small"
                  @click="viewRejectReason(api)"
                ></el-button>
              </el-tooltip>
              
              <el-tooltip content="重新发布" placement="top">
                <el-button 
                  type="success" 
                  icon="el-icon-refresh"
                  circle
                  size="small"
                  @click="reSubmitApi(api)"
                ></el-button>
              </el-tooltip>
            </template>
            
            <!-- 正常状态显示下架按钮 -->
            <el-tooltip 
              content="下架" 
              placement="top"
              v-if="api.status === 1"
            >
              <el-button 
                type="danger"
                icon="el-icon-download"
                circle
                size="small"
                @click="toggleApiStatus(api)"
              ></el-button>
            </el-tooltip>
          </div>
        </div>

        <div class="api-content">
          <p class="api-description">{{ api.description }}</p>
          <div class="api-meta">
            <span>
              <i class="el-icon-connection"></i> {{ api.rqsType }}
            </span>
            <span>
              <i class="el-icon-link"></i> {{ api.apiurl }}
            </span>
            <span v-if="api.updatetime">
              <i class="el-icon-time"></i> {{ formatDate(api.updatetime) }}
            </span>
            <!-- 显示发布模式(仅预发布和正式发布状态) -->
            <!-- 显示发布模式和限制 -->
  <span v-if="api.mode">
    <i class="el-icon-data-analysis"></i> 
    {{ api.mode === 'gray' ? '灰度发布' : '全量发布' }}
    <span v-if="api.mode === 'gray' && api.apiLimit">
      (阈值: {{ api.apiLimit }})
    </span>
  </span>
</div>
          
<!-- 更新API统计区域，显示调用次数和剩余次数 -->
<div class="api-stats">
  <div class="stat-item">
    <span class="stat-label">调用次数</span>
    <span class="stat-value">
      {{ api.apiRequestCount || 0 }}
      <span v-if="api.mode === 'gray' && api.apiLimit" 
        :class="{'warning-text': isNearLimit(api), 'danger-text': isAtLimit(api)}">
        (剩余: {{ Math.max(0, api.apiLimit - api.apiRequestCount) }})
      </span>
    </span>
  </div>
         
            <div class="stat-item">
              <span class="stat-label">响应类型</span>
              <span class="stat-value">{{ api.resType }}</span>
            </div>
            <!-- 添加接近或达到限制时的警告提示 -->
<div v-if="isAtLimit(api)" class="api-warning">
  <i class="el-icon-warning"></i>
  <span>该接口已达到调用上限，请重新配置或下架！</span>
  <div class="warning-actions">
    <el-button type="warning" size="mini" @click="configurePublish(api)">重新配置</el-button>
    <el-button type="danger" size="mini" @click="toggleApiStatus(api)">下架接口</el-button>
  </div>
</div>
<div v-else-if="isNearLimit(api)" class="api-warning near-limit">
  <i class="el-icon-warning"></i>
  <span>该接口即将达到调用上限，请及时重新配置！</span>
</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showDialog"
      width="50%"
      :close-on-click-modal="false"
      custom-class="edit-dialog"
    >
      <!-- 编辑表单内容 -->
      <el-form :model="apiForm" ref="apiForm" :rules="apiRules" label-width="100px">
        <!-- 表单内容 -->
      </el-form>
      <div slot="footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitApiForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 审核失败原因对话框 -->
    <el-dialog
      title="审核失败原因"
      :visible.sync="showRejectReasonDialog"
      width="40%"
      custom-class="reject-reason-dialog"
    >
      <div class="reject-reason-content">
        <i class="el-icon-warning-outline reject-icon"></i>
        <div class="reason-text">{{ currentRejectReason }}</div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="showRejectReasonDialog = false">确定</el-button>
      </div>
    </el-dialog>

    <!-- 参数配置对话框 -->
    <el-dialog
      title="配置参数"
      :visible.sync="showParameterDialog"
      width="70%"
      :close-on-click-modal="false"
      :modal-append-to-body="true"
      append-to-body
      :destroy-on-close="true"
      custom-class="parameter-dialog"
    >
      <div class="parameters-container">
        <!-- 参数列表 -->
        <div class="parameters-list">
          <el-table :data="parameters" border style="width: 100%">
            <el-table-column prop="paramName" label="参数名" width="150"></el-table-column>
            <el-table-column prop="paramType" label="参数类型" width="120"></el-table-column>
            <el-table-column prop="isRequired" label="是否必填" width="100">
              <template slot-scope="scope">
                {{ scope.row.isRequired ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column prop="paramDirection" label="参数类型" width="100">
              <template slot-scope="scope">
                {{ scope.row.paramDirection === '1' ? '入参' : '出参' }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column prop="example" label="示例"></el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  circle
                  @click="removeParameter(scope.$index)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 添加参数表单 -->
        <div class="parameter-form">
          <el-divider>添加参数</el-divider>
          <el-form :model="parameterForm" ref="parameterForm" :rules="parameterRules" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="参数名" prop="paramName">
                  <el-input v-model="parameterForm.paramName" placeholder="请输入参数名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="参数类型" prop="paramType">
                  <el-select v-model="parameterForm.paramType" placeholder="请选择参数类型">
                    <el-option label="String" value="String"></el-option>
                    <el-option label="Number" value="Number"></el-option>
                    <el-option label="Boolean" value="Boolean"></el-option>
                    <el-option label="Object" value="Object"></el-option>
                    <el-option label="Array" value="Array"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="入参/出参" prop="paramDirection">
                  <el-select v-model="parameterForm.paramDirection" placeholder="请选择">
                    <el-option label="入参" value="1"></el-option>
                    <el-option label="出参" value="0"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="是否必填" prop="isRequired">
                  <el-switch v-model="parameterForm.isRequired" active-text="是" inactive-text="否"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="parameterForm.remark" placeholder="请输入备注"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="示例" prop="example">
                  <el-input v-model="parameterForm.example" placeholder="请输入示例"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="addParameter">添加参数</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="showParameterDialog = false">取消</el-button>
        <el-button type="primary" @click="submitParameters">保存配置</el-button>
      </div>
    </el-dialog>

    <!-- 发布配置对话框 -->
    <el-dialog
  title="配置发布模式"
  :visible.sync="showPublishConfigDialog"
  width="50%"
  :close-on-click-modal="false"
  :modal-append-to-body="true"
  append-to-body
  :destroy-on-close="true"
  custom-class="publish-config-dialog"
>
      <el-form :model="publishConfigForm" ref="publishConfigForm" :rules="publishConfigRules" label-width="120px">
        
         <!-- 版本信息配置 -->
    <el-form-item label="Version" prop="version">
      <el-input
        v-model="publishConfigForm.version"
        placeholder="Enter version number"
        style="width: 220px"
      >
        <template slot="prepend">
          <el-dropdown @command="handleVersionSelect">
            <span class="el-dropdown-link">
              Quick Select<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item 
                v-for="(version, index) in versionTemplates" 
                :key="index"
                :command="version.value"
              >
                {{ version.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-input>
      <div class="form-tip">Format: v1.0.0 (Major.Minor.Patch)</div>
    </el-form-item>
        <el-form-item label="发布模式" prop="publishType">
          <el-radio-group v-model="publishConfigForm.publishType">
            <el-radio label="full">全量发布</el-radio>
            <el-radio label="gray">灰度发布</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item 
          label="请求次数阈值" 
          prop="requestThreshold"
          v-if="publishConfigForm.publishType === 'gray'"
        >
          <el-input-number 
            v-model="publishConfigForm.requestThreshold" 
            :min="1" 
            :max="10000"
            :step="10"
          ></el-input-number>
          <div class="form-tip">设置灰度发布的请求次数阈值，达到阈值后将自动切换为全量发布</div>
        </el-form-item>
      </el-form>
      
      <div slot="footer">
        <el-button @click="showPublishConfigDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPublishConfig">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'MyApi',
  data() {
   // 添加版本号验证规则
   const validateVersion = (rule, value, callback) => {
    const pattern = /^v\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/
    if (!pattern.test(value)) {
      callback(new Error('Invalid version format. Example: v1.0.0 or v1.0.0-beta'))
    } else {
      callback()
    }
  }
    return {
      loading: false,
      // 统计数据
      stats: {
        published: 0,
        offline: 0,
        draft: 0
      },
      // 搜索和筛选
      searchQuery: '',
      statusFilter: '',
      // API 列表 - 添加一些初始测试数据
      apis: [
        {
          apiid: 1,
          name: '测试API-1',
          description: '这是一个测试API接口',
          rqsType: 'GET',
          apiurl: '/api/test1',
          status: 1,
          updatetime: '2024-03-20',
          call: 1000,
          resType: 'JSON',
          publishType: 'full'
        },
        {
          apiid: 2, 
          name: '测试API-2',
          description: '这是另一个测试API接口',
          rqsType: 'POST',
          apiurl: '/api/test2',
          status: 0,
          updatetime: '2024-03-19',
          call: 500,
          resType: 'JSON'
        },
        {
          apiid: 3, 
          name: '测试API-3',
          description: '这是一个预发布状态的测试API接口',
          rqsType: 'POST',
          apiurl: '/api/test3',
          status: 20,
          updatetime: '2024-03-21',
          call: 50,
          resType: 'JSON',
          publishType: 'gray',
          requestThreshold: 200
        }
      ],
      showDialog: false,
      dialogType: 'create',
      apiForm: {
        name: '',
        rqsType: 'GET',
        apiurl: '',
        testurl: '',
        description: '',
        resType: 'JSON',
        note: '无',
        isneedtoken: 0
      },
      apiRules: {
        name: [
          { required: true, message: '请输入接口名称', trigger: 'blur' }
        ],
        apiurl: [
          { required: true, message: '请输入接口地址', trigger: 'blur' }
        ],
        testurl: [
          { required: true, message: '请输入测试地址', trigger: 'blur' }
        ]
      },
      showRejectReasonDialog: false,
      currentRejectReason: '',
      
      // 参数配置相关
      showParameterDialog: false,
      currentApi: null,
      parameters: [],
      parameterForm: {
        paramName: '',
        paramType: '',
        isRequired: true,
        paramDirection: '1',
        remark: '',
        example: ''
      },
      parameterRules: {
        paramName: [{ required: true, message: '请输入参数名', trigger: 'blur' }],
        paramType: [{ required: true, message: '请选择参数类型', trigger: 'change' }],
        paramDirection: [{ required: true, message: '请选择入参或出参', trigger: 'change' }],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
        example: [{ required: true, message: '请输入示例', trigger: 'blur' }]
      },
      
      // 发布配置相关
      showPublishConfigDialog: false,
      publishConfigForm: {
      apiId: null,
      publishType: 'full',
      requestThreshold: 100,
      version: ''  // 新增版本字段
    },
    // 版本快捷选择模板
    versionTemplates: [
      { label: 'Major Release', value: 'v1.0.0' },
      { label: 'Minor Release', value: 'v0.1.0' },
      { label: 'Patch Release', value: 'v0.0.1' },
      { label: 'Alpha Version', value: 'v1.0.0-alpha' },
      { label: 'Beta Version', value: 'v1.0.0-beta' },
      { label: 'Release Candidate', value: 'v1.0.0-rc' },
      { label: 'Development Version', value: 'v1.0.0-dev' },
      { label: 'Nightly Build', value: 'v1.0.0-nightly' },
      { label: 'Preview Version', value: 'v1.0.0-preview' },
      { label: 'Snapshot Version', value: 'v1.0.0-snapshot' }
    ],
    // 更新验证规则，添加版本验证
    publishConfigRules: {
      version: [
        { required: true, message: 'Please enter version number', trigger: 'blur' },
        { validator: validateVersion, trigger: 'blur' }
      ],
      publishType: [
        { required: true, message: 'Please select release type', trigger: 'change' }
      ],
      requestThreshold: [
        { required: true, message: 'Please set request threshold', trigger: 'blur' },
        { type: 'number', min: 1, message: 'Threshold must be greater than 0', trigger: 'blur' }
      ]
    },
      publishConfigRules: {
        publishType: [
          { required: true, message: '请选择发布类型', trigger: 'change' }
        ],
        requestThreshold: [
          { required: true, message: '请设置请求次数阈值', trigger: 'blur' },
          { type: 'number', min: 1, message: '阈值必须大于0', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    dialogTitle() {
      return this.dialogType === 'create' ? '创建新接口' : '编辑接口'
    },
    filteredApis() {
      return this.apis.filter(api => {
        const matchQuery = api.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
                         api.description.toLowerCase().includes(this.searchQuery.toLowerCase())
        const matchStatus = !this.statusFilter || api.status.toString() === this.statusFilter
        return matchQuery && matchStatus
      })
    }
  },

  methods: {
    // 检查是否接近限制（剩余次数少于20%）
  isNearLimit(api) {
    if (api.mode !== 'gray' || !api.apiLimit) return false;
    const remaining = api.apiLimit - api.apiRequestCount;
    return remaining > 0 && remaining < api.apiLimit * 0.2;
  },
  
  // 检查是否已达到限制
  isAtLimit(api) {
    if (api.mode !== 'gray' || !api.apiLimit) return false;
    return api.apiRequestCount >= api.apiLimit;
  },
    // 在fetchApis方法中添加获取调用次数和限制信息的处理
  async fetchApis() {
    this.loading = true;
    try {
      const response = await axios.get('/api/system/api/author/getApiList');
      this.apis = response.data.data || [];
      
      // 获取每个API的调用次数和限制信息
      for (let api of this.apis) {
        if (api.apiid) {
          try {
            const statsResponse = await axios.get(`/api/system/api/stats/${api.apiid}`);
            const stats = statsResponse.data.data || {};
            
            // 更新API信息
            api.apiRequestCount = stats.apiRequestCount || 0;
            api.mode = stats.mode || null;
            api.apiLimit = stats.apiLimit || null;
          } catch (error) {
            console.error(`获取API ${api.apiid} 统计信息失败:`, error);
          }
        }
      }
      
      this.updateStats();
    } catch (error) {
      this.$message.error('获取接口列表失败: ' + error.message);
    } finally {
      this.loading = false;
    }
  },

    // 更新统计数据
    updateStats() {
      this.stats = {
        published: this.apis.filter(api => api.status === 1).length,
        offline: this.apis.filter(api => api.status === 0).length,
        draft: this.apis.filter(api => ['-1','-2'].includes(api.status?.toString())).length
      }
    },

    // 创建新接口
    createApi() {
      this.dialogType = 'create'
      this.apiForm = {
        name: '',
        rqsType: 'GET',
        apiurl: '',
        testurl: '',
        description: '',
        resType: 'JSON',
        note: '无',
        isneedtoken: 0
      }
      this.showDialog = true
    },

    // 编辑接口
    editApi(api) {
      this.dialogType = 'edit'
      this.apiForm = { ...api }
      this.showDialog = true
    },

    // 提交表单
    async submitApiForm() {
      try {
        await this.$refs.apiForm.validate()
        const url = this.dialogType === 'create' 
          ? '/api/system/api/author/create'
          : `/api/system/api/author/update/${this.apiForm.apiid}`
        
        const method = this.dialogType === 'create' ? 'post' : 'put'
        await axios[method](url, this.apiForm)
        
        this.$message.success(`${this.dialogType === 'create' ? '创建' : '更新'}成功`)
        this.showDialog = false
        this.fetchApis()
      } catch (error) {
        this.$message.error('提交失败: ' + error.message)
      }
    },

    // 切换接口状态
    async toggleApiStatus(api) {
      try {
        await this.$confirm('确定要下架该接口吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await axios.put(`/api/system/api/author/offline/${api.apiid}`)
        this.$message.success('下架成功')
        this.fetchApis()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('操作失败: ' + error.message)
        }
      }
    },

    // 查看审核失败原因
    async viewRejectReason(api) {
      try {
        const res = await axios.get(`/api/system/api/apiReject/${api.apiid}`)
        this.currentRejectReason = res.data.data.reject || '未提供具体原因'
        this.showRejectReasonDialog = true
      } catch (error) {
        this.$message.error('获取失败原因失败: ' + error.message)
      }
    },

    // 重新提交审核
    async reSubmitApi(api) {
      try {
        await axios.post(`/api/system/api/author/reSubmit/${api.apiid}`)
        this.$message.success('重新提交成功，请等待审核')
        this.fetchApis()
      } catch (error) {
        this.$message.error('重新提交失败: ' + error.message)
      }
    },

    // 获取卡片样式类
    getCardClass(status) {
      return {
        'api-card-error': status === 0,
        'api-card-review-failed': status === -3,
        'api-card-prepublish': status === 20 // 预发布状态样式
      }
    },

    // 获取状态类型
    getStatusType(status) {
      const typeMap = {
        '0': 'danger',
        '1': 'success',
        '2': 'warning',
        '5': 'success',
        '-1': 'info',
        '-2': 'warning',
        '-3': 'danger',
        '10': 'info',
        '20': 'warning' // 预发布状态
      }
      return typeMap[status] || 'info'
    },

    // 获取状态标签
    getStatusLabel(status) {
      const labelMap = {
        '0': '异常',
        '1': '正常',
        '2': '升级中',
        '5': '审核成功',
        '-1': '待发布',
        '-2': '待审核',
        '-3': '审核失败',
        '10': '参数待配置',
        '20': '预发布'
      }
      return labelMap[status] || '未知状态'
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '暂无'
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    },

    // 参数配置相关方法
    configureParameters(api) {
      this.currentApi = api;
      this.parameters = []; // 清空参数列表
      this.parameterForm = {
        paramName: '',
        paramType: '',
        isRequired: true,
        paramDirection: '1',
        remark: '',
        example: ''
      };
      // 如果需要，这里可以添加获取已有参数配置的逻辑
      this.showParameterDialog = true;
    },

    // 添加参数
    async addParameter() {
      try {
        await this.$refs.parameterForm.validate();
        this.parameters.push({...this.parameterForm});
        this.$refs.parameterForm.resetFields();
        this.$message.success('参数添加成功');
      } catch (error) {
        // 表单验证失败
      }
    },

    // 删除参数
    removeParameter(index) {
      this.$confirm('确认删除该参数?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.parameters.splice(index, 1);
        this.$message.success('删除成功');
      }).catch(() => {});
    },

    // 保存所有参数配置
    async submitParameters() {
      if (this.parameters.length === 0) {
        this.$message.warning('请至少添加一个参数');
        return;
      }
      try {
        // 这里添加提交参数列表到后端的逻辑
        await axios.post('/api/system/api/params/save', {
          apiId: this.currentApi.apiid,
          parameters: this.parameters
        });
        this.$message.success('参数配置保存成功');
        this.showParameterDialog = false;
        this.fetchApis();
      } catch (error) {
        this.$message.error('保存失败: ' + error.message);
      }
    },

    // 版本快捷选择处理方法
  handleVersionSelect(version) {
    this.publishConfigForm.version = version
  },
  
  // 更新配置发布方法
  configurePublish(api) {
    this.publishConfigForm = {
      apiId: api.apiid,
      publishType: api.publishType || 'full',
      requestThreshold: api.requestThreshold || 100,
      version: api.version || 'v1.0.0'  // 添加版本号初始化
    }
    this.showPublishConfigDialog = true
  },

    // 提交发布配置
    async submitPublishConfig() {
      try {
        await this.$refs.publishConfigForm.validate();
        
        // 发送请求保存发布配置
        await axios.post('/api/system/api/author/configPublish', this.publishConfigForm);
        
        this.$message.success('发布配置已保存');
        this.showPublishConfigDialog = false;
        this.fetchApis(); // 刷新API列表
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('保存失败: ' + error.message);
        }
      }
    },
    // 发布API
  async publishApi(api) {
    try {
      await this.$confirm('确定要发布该接口吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await axios.post(`/api/system/api/author/publish/${api.apiid}`)
      this.$message.success('发布成功')
      this.fetchApis()
    } catch (error) {
      if (error !== 'cancel') {
        this.$message.error('发布失败: ' + error.message)
      }
    }
  }

  },

  mounted() {
    this.fetchApis()
  }
}
</script>

<style scoped>
.api-management {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.glass-effect {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.page-header {
  padding: 24px;
  border-radius: 12px;
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-content h1 {
  margin: 0;
  font-size: 24px;
  color: #1a237e;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: rgba(64, 158, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.stat-icon i {
  font-size: 24px;
  color: #409EFF;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1a237e;
}

.stat-label {
  color: #666;
  margin-top: 4px;
}

.filter-section {
  display: flex;
  gap: 16px;
  padding: 16px;
  border-radius: 12px;
  margin-bottom: 24px;
}

.search-input {
  flex: 1;
}

.status-filter {
  width: 150px;
}

.api-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.api-card {
  border-radius: 12px;
  transition: all 0.3s ease;
}

.api-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
}

.api-card-error {
  border-left: 4px solid #F56C6C;
}

.api-card-review-failed {
  border-left: 4px solid #E6A23C;
}

.api-card-prepublish {
  border-left: 4px solid #E6A23C;
}

.api-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.api-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.api-title h3 {
  margin: 0;
  font-size: 18px;
  color: #1a237e;
}

.api-actions {
  display: flex;
  gap: 8px;
}

.api-description {
  color: #666;
  margin: 0 0 16px;
  line-height: 1.5;
}

.api-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  color: #666;
  font-size: 14px;
  margin-bottom: 16px;
}

.api-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.api-stats {
  display: flex;
  gap: 24px;
  padding-top: 16px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.api-stats .stat-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.api-stats .stat-label {
  color: #666;
  font-size: 14px;
}

.api-stats .stat-value {
  color: #1a237e;
  font-weight: 500;
}

.reject-reason-dialog .reject-reason-content {
  padding: 20px;
  text-align: center;
}

.reject-reason-dialog .reject-icon {
  font-size: 48px;
  color: #E6A23C;
  margin-bottom: 20px;
}

.reject-reason-dialog .reason-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-all;
  text-align: left;
  background: #fdf6ec;
  padding: 15px;
  border-radius: 4px;
  border-left: 4px solid #E6A23C;
}

/* 参数配置对话框样式 */
.parameter-dialog {
  z-index: 3000 !important; /* 确保对话框在蒙版之上 */
}

/* 参数配置表单样式 */
.parameters-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.parameters-list {
  margin-bottom: 20px;
}

.parameter-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

/* 发布配置对话框样式 */
.publish-config-dialog .form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

@media screen and (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }

  .api-list {
    grid-template-columns: 1fr;
  }

  .filter-section {
    flex-direction: column;
  }

  .status-filter {
    width: 100%;
  }
}
/* 警告提示样式 */
.api-warning {
  margin-top: 16px;
  padding: 12px;
  border-radius: 4px;
  background-color: #fef0f0;
  color: #f56c6c;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.api-warning.near-limit {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.api-warning i {
  margin-right: 8px;
}

.warning-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.warning-text {
  color: #e6a23c;
  font-weight: bold;
}

.danger-text {
  color: #f56c6c;
  font-weight: bold;
}
</style>